package com.himiotech.core.project.web;

import cn.hutool.json.JSONUtil;
import com.himiotech.core.framework.config.HimioConfig;
import com.himiotech.core.framework.helper.anno.RepeatSubmit;
import com.himiotech.core.framework.helper.utils.ServletUtils;
import com.himiotech.core.project.service.IConfigService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Controller
public class LoginController extends HimioBaseController {

    @Autowired
    private IConfigService configService;
    @Autowired
    private HimioConfig himioConfig;

    @GetMapping("/login")
    public String login(HttpServletRequest request) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, JSONUtil.toJsonStr(writeJsonErr("未登录或超时。请重新登录")));
        }
        request.setAttribute("bg", configService.selectConfigByKey("sys.loginPage.url"));
        request.setAttribute("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        request.setAttribute("footerText", configService.selectConfigByKey("sys.index.footerText"));
        request.setAttribute("copyrightYear", himioConfig.getCopyrightYear());
        request.setAttribute("icp", configService.selectConfigByKey("sys.index.icp"));
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    @RepeatSubmit
    public HimioResult ajaxLogin(String username, String password, Boolean rememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return writeJsonOk();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return writeJsonErr(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/403";
    }
}
